package Lee_code;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

/**
 * @author blh
 * @date 2024年08月04日 9:25
 */
public class Lee_670_84 {
    public int maximumSwap(int num) {
        String str = String.valueOf(num);
        Deque<Integer> res = new ArrayDeque<>();
        char[] chars = str.toCharArray();
        // 记录一下两个位置
        int left = 0, right = 0;
        int change = 0;
        for (int i = 0; i < str.toCharArray().length; i++) {
            if (res.isEmpty()) {
                res.offer(i);
            } else if (chars[i] <= chars[res.peekLast()] && change == 0) {
                res.offer(i);
            } else if (chars[i] > chars[res.peekLast()]) {
                while (!res.isEmpty() && chars[i] > chars[res.peekLast()]){
                    right = i;
                    left = res.pollLast();
                    chars[left] = chars[right];
                }
                res.offer(left);
                change = 1;
            }
        }
        char[] resChar = str.toCharArray();
        char temp = resChar[right];
        resChar[right] = resChar[left];
        resChar[left] = temp;
        StringBuilder realSb = new StringBuilder();
        for (char c : resChar) {
            realSb.append(c);
        }
        return Integer.parseInt(realSb.toString());
    }
}
